package com.fir.my.batis.plus.task;

import com.fir.my.batis.plus.mapper.DetectionRlMapper;
import com.fir.my.batis.plus.mapper.YourRepository;
import com.fir.my.batis.plus.until.DateUtil;
import com.sun.nio.file.SensitivityWatchEventModifier;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.file.*;
import java.util.*;

/**
 * 监听文件更新，不包含子目录
 *
 * 参考 https://zhuanlan.zhihu.com/p/521808292?utm_id=0
 */
@Component
//@Order(2)
@Slf4j
public class WatchServiceDemo_Access {
    @Autowired
    DetectionRlMapper detectionRlMapper;
    @Autowired
    YourRepository yourRepository;

    @Value("${accessPath}")
    private String accessPath;

    public void init() throws IOException {
        log.info(accessPath);
        Path path = Paths.get(accessPath);//        Path path = Paths.get("D:/上位机/DATA/");//默认
        WatchService watcher = FileSystems.getDefault().newWatchService();
        path.register(watcher, new WatchEvent.Kind[]{StandardWatchEventKinds.ENTRY_MODIFY},SensitivityWatchEventModifier.HIGH);
        path.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
        try {
            while (true) {
                WatchKey key = watcher.take();
                for (WatchEvent<?> event : key.pollEvents()) {
                    if (event.kind() == StandardWatchEventKinds.OVERFLOW) {
                        continue;
                    }
                    Path fileName = (Path) event.context();
                    log.info("文件更新: " + fileName);
                    String lastTime = detectionRlMapper.getLastTime();
                    if(null == lastTime){
                        lastTime = DateUtil.sdf.format(new Date());
                        lastTime = DateUtil.sdf.format(DateUtil.getCutDay(-1));
                    }
                    log.info("最新时间" + lastTime);
                    String rq = lastTime.split(" ")[0];
                    String time = lastTime.split(" ")[1].substring(0,5);
                    /**
                     * 读取access数据库数据  main.mdb 中 GPdata表
                     */
                    String file = accessPath  + fileName;
                    log.info("读取file" + file);
                    List<Map<String, Object>> all = yourRepository.findAll(rq,time);
                    HashMap<String, Map<String, Object>> data = actData(all);
//                    log.info("mdb数据:" + data.toString());
                    if(data.size() == 0){
                        log.info("最新”无数据");
                        return ;
                    }
                    List<Map<String,Object>> list = new ArrayList<>();
                    for (Map.Entry<String, Map<String, Object>> stringMapEntry : data.entrySet()) {
                        list.add(stringMapEntry.getValue());//hashMap转 list<json>
                    }
                    log.info("mdb处理后的jsonList:" + list.toString());
                    /**
                     * 写入库 tb_detection_rl
                     */
                    int i = detectionRlMapper.insertDetectionBetch(list);
                    log.info("写入" + i +"条数据==");
                }
                if (!key.reset()) {
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public HashMap<String,Map<String, Object>>  actData(List<Map<String, Object>> initList ){
//        List<Map<String, Object>> mdbEntityList = MdbUtil.resolverMdb(mdbPath, mdbSql, columns);
        log.info(initList.toString());
        HashMap<String,Map<String, Object>> keyobj = new HashMap();
        for(Map<String, Object> row : initList){
            String DATE = row.get("DATE").toString();
            String TIME = row.get("TIME").toString();
            String YP = row.get("YP").toString();
            String YSNa = row.get("YSNa").toString();
            String YSVal = row.get("YSVal").toString();
            String key = DATE + " "+ TIME +" "  +  YP ;//时间 加炉次号：  2019-04-20 22:24 B-026-C1
            String furnace_num = YP.substring(0,1);
            String lch = "";
            String[] split = YP.split("-");//B-026-C1 | A14-0
            if(split.length > 1){
                if(split[0].length() > 1){
                    lch = split[0].substring(1);
                }else{
                    lch = split[1] ;
                }
            }
            String melt_num = YP.substring(1);
            if(keyobj.get(key) == null){
                HashMap<String,Object> item = new HashMap<>();
                item.put("DATE",DATE);
                item.put("TIME",TIME);
                item.put("storage_time",DATE + " " + TIME + ":00");
                item.put("remark","cron_watch");
                item.put("mark_id","350-10");
                item.put("YP",YP);
                item.put("furnace_num",furnace_num);//B
                item.put("melt_num",melt_num);
                item.put("lch",lch);//26
                item.put(YSNa,YSVal);
                keyobj.put(key,item);
            }else{
                Map<String, Object> item = keyobj.get(key);
                item.put(YSNa,YSVal);
                keyobj.put(key,item);
                //2023-12-14 06:13 C16-0={Mn=0.4410, Cd=0.0000, Mo=0.0020, B=0.0023,
                // Ce=0.0026, C=3.1028, Al=0.0000, Cr=0.0440, P=0.0337, Cu=0.0459, As=0.0040, Pb=0.0000,
                // S=0.0374, Zn=0.0029, Ti=0.0128, La=0.0253, V=0.0073, YP=C16-0, Ni=0.0138, Fe=94.7027,
                // Bi=0.0019, TIME=06:13,
                // Sb=0.0000, DATE=2023-12-14, Si=1.5107, Mg=0.0000, Sn=0.0060, Ca=0.0008}
            }
        }

        return keyobj;
    }


}
